var ramSize = [];
var spaceName;
var spaceSize = 0;
var delPid;
var ramInfoList = [];

var useRam = 0;
var freeRam = 0;

function apply() {
	let size = $('#ramSize').val();
	size = size*1024;
	freeRam = size;
	//把所有的全部初始化为0
	ramSize =  Array.apply(null,Array(size)).map(function(item, i) {
    	return 0;
	});
	printText('内存创建成功！\n');
}
function getInputInfo(){
	spaceName = $('#spaceName').val();
	spaceSize = $('#spaceSize').val();
	spaceSize = Number(spaceSize);
}
function start(){
	getInputInfo();
	if(spaceSize >freeRam){
		printText('无空间存储该进程\n');
	}else{
		savePro();
	}
}

function getPropid(){
	const timeId = Date.now();
	const pid =  timeId.toString(16);
	return pid;
}
//首次适应算法
function savePro(){
	var index = 0;
	var start = 0;
	var end = 0;
	for(var i=0;i<ramSize.length;i++){
		if(index == spaceSize){
			const ramObj = new Object();
			ramObj.name = spaceName;
			ramObj.size = spaceSize;
			ramObj.start = start+1;
			ramObj.end = i + 1;
			ramObj.pid = getPropid();
			ramObj.state  = '已分配'
			useRam += spaceSize;
			freeRam -= spaceSize;
			ramInfoList.push(ramObj);
			for(var j = start;j<spaceSize+start+1;j++){
				ramSize[j] = 1;
			}
			showPro();
			break;
		}
		if(ramSize[i] === 0){
			index++;
		}
		if(ramSize[i] != 0){
			start = i;
			index = 0;
		}
	}
}
function delPro(){
	delPid = $('#delPid').val();
	var delProInfo = new Object();
	var index = 0;
	console.log(ramInfoList);
	for(var i =0;i<ramInfoList.length;i++){
		if(ramInfoList[i].pid == delPid){
			ramInfoList[i].state = '空闲'
			delProInfo = ramInfoList[i];
			index = i;
			break;
		}
	}
	if(i == ramInfoList.length){
		printText('不存在该进程！\n');
	}else{
		
		for(var j = delProInfo.start;j<delProInfo.end;j++){
			ramSize[j] = 0;
		}
		useRam = useRam - delProInfo.size;
		freeRam = freeRam + delProInfo.size;
		printText('进程删除成功\n');
		showPro();
	}
}
function showPro(){
	printText('进程名'+"     "+'PID'+"     "+"进程大小"+'     '+'启始结束位置' + '     ' + '状态\n')
	for(var i=0;i<ramInfoList.length;i++){
		printText(ramInfoList[i].name + "     "+ramInfoList[i].pid+"     "+ramInfoList[i].size+'     '+ ramInfoList[i].start+ '-'+ramInfoList[i].end +'     '+ramInfoList[i].state+'\n')
	}
	printText('内存大小：'+ $('#ramSize').val()*1024 + 'kb\n')
	printText('已用内存：'+ useRam + 'kb\n');
	printText('剩余内存：'+ freeRam + 'kb\n');
}

function printText(str) {
	$("#print").append(str);
}